/**
 * 成就列表组件
 * 展示用户的成就进度和解锁状态
 */
import React, { useEffect, useState } from 'react';
import {
  Card,
  List,
  Progress,
  Tag,
  Tabs,
  Empty,
  Badge,
  Tooltip,
  Space,
  Typography,
} from 'antd';
import {
  TrophyOutlined,
  LockOutlined,
  CheckCircleOutlined,
  GiftOutlined,
} from '@ant-design/icons';
import { useStatisticsStore } from '@/stores/statistics.store';
import { ACHIEVEMENT_CATEGORIES } from '@/constants/achievements';
import type { Achievement } from '@/types/statistics';
import './style.css';

const { Text, Title } = Typography;

interface AchievementListProps {
  className?: string;
  showCategory?: boolean;
}

export const AchievementList: React.FC<AchievementListProps> = ({
  className,
  showCategory = true,
}) => {
  const { achievements, loading, loadAchievements } = useStatisticsStore();
  const [selectedCategory, setSelectedCategory] = useState<Achievement['category'] | 'all'>(
    'all'
  );

  useEffect(() => {
    loadAchievements();
  }, [loadAchievements]);

  // 按分类过滤成就
  const filteredAchievements =
    selectedCategory === 'all'
      ? achievements
      : achievements.filter((ach) => ach.category === selectedCategory);

  // 统计各分类的成就数量
  const categoryStats = React.useMemo(() => {
    const stats: Record<string, { total: number; unlocked: number }> = {};

    Object.keys(ACHIEVEMENT_CATEGORIES).forEach((category) => {
      const categoryAchievements = achievements.filter(
        (ach) => ach.category === category
      );
      stats[category] = {
        total: categoryAchievements.length,
        unlocked: categoryAchievements.filter((ach) => ach.unlocked).length,
      };
    });

    return stats;
  }, [achievements]);

  // 渲染成就卡片
  const renderAchievementItem = (achievement: Achievement) => {
    const isUnlocked = achievement.unlocked;
    const hasProgress = achievement.progress !== undefined && achievement.total !== undefined;
    const progressPercent = hasProgress
      ? Math.min((achievement.progress! / achievement.total!) * 100, 100)
      : 0;

    return (
      <List.Item className={`achievement-item ${isUnlocked ? 'unlocked' : 'locked'}`}>
        <Card hoverable>
          <div className="achievement-content">
            {/* 图标和状态 */}
            <div className="achievement-icon">
              <Badge
                count={
                  isUnlocked ? (
                    <CheckCircleOutlined style={{ color: '#52c41a', fontSize: 16 }} />
                  ) : undefined
                }
                offset={[-8, 8]}
              >
                <div className={`icon-wrapper ${isUnlocked ? '' : 'grayscale'}`}>
                  <span className="icon-emoji">{achievement.icon}</span>
                </div>
              </Badge>
            </div>

            {/* 成就信息 */}
            <div className="achievement-info">
              <Space direction="vertical" size={4} style={{ width: '100%' }}>
                <div className="achievement-header">
                  <Text strong className="achievement-name">
                    {achievement.name}
                  </Text>
                  <Tag color={ACHIEVEMENT_CATEGORIES[achievement.category].color}>
                    {ACHIEVEMENT_CATEGORIES[achievement.category].label}
                  </Tag>
                </div>

                <Text type="secondary" className="achievement-description">
                  {achievement.description}
                </Text>

                {/* 进度条 */}
                {hasProgress && (
                  <div className="achievement-progress">
                    <Progress
                      percent={progressPercent}
                      size="small"
                      status={isUnlocked ? 'success' : 'active'}
                      format={() =>
                        `${achievement.progress}/${achievement.total}`
                      }
                    />
                  </div>
                )}

                {/* 奖励信息 */}
                {achievement.rewards && (
                  <Space size={8} className="achievement-rewards">
                    {achievement.rewards.xp && (
                      <Tooltip title="经验值">
                        <Tag icon={<TrophyOutlined />} color="gold">
                          +{achievement.rewards.xp} XP
                        </Tag>
                      </Tooltip>
                    )}
                    {achievement.rewards.badge && (
                      <Tooltip title="称号">
                        <Tag icon={<GiftOutlined />} color="purple">
                          {achievement.rewards.badge}
                        </Tag>
                      </Tooltip>
                    )}
                  </Space>
                )}

                {/* 解锁时间 */}
                {isUnlocked && achievement.unlockedAt && (
                  <Text type="secondary" className="achievement-unlocked-time">
                    解锁于 {new Date(achievement.unlockedAt).toLocaleDateString()}
                  </Text>
                )}

                {/* 未解锁提示 */}
                {!isUnlocked && (
                  <Text type="secondary" className="achievement-locked-hint">
                    <LockOutlined /> 尚未解锁
                  </Text>
                )}
              </Space>
            </div>
          </div>
        </Card>
      </List.Item>
    );
  };

  // 分类标签项
  const tabItems = [
    {
      key: 'all',
      label: (
        <span>
          <TrophyOutlined /> 全部 ({achievements.length})
        </span>
      ),
    },
    ...Object.entries(ACHIEVEMENT_CATEGORIES).map(([key, info]) => ({
      key,
      label: (
        <span>
          {info.icon} {info.label} ({categoryStats[key]?.unlocked || 0}/
          {categoryStats[key]?.total || 0})
        </span>
      ),
    })),
  ];

  return (
    <div className={`achievement-list ${className || ''}`}>
      <Card
        title={
          <Space>
            <TrophyOutlined />
            <span>成就系统</span>
          </Space>
        }
        extra={
          <Text type="secondary">
            已解锁 {achievements.filter((a) => a.unlocked).length}/{achievements.length}
          </Text>
        }
      >
        {showCategory && (
          <Tabs
            activeKey={selectedCategory}
            onChange={(key) => setSelectedCategory(key as Achievement['category'] | 'all')}
            items={tabItems}
            className="achievement-tabs"
          />
        )}

        <List
          loading={loading}
          dataSource={filteredAchievements}
          renderItem={renderAchievementItem}
          locale={{
            emptyText: (
              <Empty
                image={Empty.PRESENTED_IMAGE_SIMPLE}
                description="暂无成就数据"
              />
            ),
          }}
          className="achievement-list-content"
        />
      </Card>
    </div>
  );
};

export default AchievementList;
